package se.sll.itintegration.catalogue.product.ejb;

import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import lombok.extern.slf4j.Slf4j;
import se.sll.itintegration.catalogue.product.entity.CodeEntity;
import se.sll.itintegration.catalogue.product.entity.CodeSystemEntity;
import se.sll.service.catalogue.common.AbstractJpaFacade;

/**
 *
 * @author khaleddaham
 */
@Slf4j
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class CodeSystemEjb extends AbstractJpaFacade<CodeSystemEntity> {

    @PersistenceContext(unitName = "productPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    @Override
    protected void setEntityManager(EntityManager em) {
        this.em = em;
    }

    public CodeSystemEjb() {
        super(CodeSystemEntity.class);
    }

    public void create(CodeEntity entity) {
        getEntityManager().persist(entity);
    }

    public void edit(CodeEntity entity) {
        getEntityManager().merge(entity);
    }

    public CodeSystemEntity findByUniqueName(String name) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public List<CodeSystemEntity> findByName(String name) {
        log.debug("CodeSystemEjb.findByName() was called");
        return super.findByAttributeValue("name", name);
    }

    public List<CodeSystemEntity> findByOid(String oid) {
        log.debug("CodeSystemEjb.findByOid() was called");
        return super.findByAttributeValue("oid", oid);
    }
    
    public CodeEntity findUniqueCode(String oid, String code){
        log.debug("CodeSystemEjb.findUniqueCode() was called");
        TypedQuery<CodeEntity> q = getEntityManager().createNamedQuery(CodeEntity.QUERY_FINDBY_OID_AND_CODE, CodeEntity.class);
        q.setParameter("oid", oid);
        q.setParameter("code", code);
        
        List<CodeEntity> ceL = q.getResultList();
        
        CodeEntity ce = null;
        if(ceL != null && ceL.size() == 1){
            ce = ceL.get(0);
        } else {
            log.error("Too many codes found: " + ceL.size() + " results.");
        }
        return ce;
    }
}
